package com.wangjw.tuling.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by wangjianwen on 2018/12/4.
 */
public class SingleThreadServer {

    private int port;

    public SingleThreadServer(int port) {
        this.port = port;
    }

    private void startServer() {
        ServerSocket serverSocket = null;
        int i = 0;
        System.out.println("服务器在端口 " + port + " 等待客户请求......");

        try {
            serverSocket = new ServerSocket(port);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                handleRequest(clientSocket, i++);
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    private void handleRequest(Socket clientSocket, int clientNo) {
        PrintStream os = null;
        BufferedReader in = null;

        try {
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            os = new PrintStream(clientSocket.getOutputStream());

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                if (inputLine.equals("Quit")) {
                    System.out.println("关闭与客户端 " + clientNo + " 的连接");
                    os.println("服务端Quit响应");
                    os.close();
                    in.close();
                    clientSocket.close();
                    break;
                } else {
                    System.out.println("来自客户端 " + clientNo + " 的输入: " + inputLine);
                    os.println("来自服务端的响应：" + inputLine);
                }
            }
        } catch (IOException e) {
            System.out.println("Stream closed");
        }
    }

    public static void main(String[] args) {
        new SingleThreadServer(8888).startServer();
    }
}
